import {
  queryAllPermission,
  getDetail,
  onDelete,
  queryUserByOrg,
  addTeamUser,
  verifyCodeFun,
  delTeam,
  submit
} from './teamMannageServ.js'
import { parse } from 'qs'
import { message } from 'antd'
import moment from 'moment'
import { isEmpty, isArray, cloneDeep, merge, get, set, concat, pick } from 'lodash'
import { hashHistory } from 'dva/router'
import AppBus from 'utils/bus'
import config from 'config/config'

const defultState = {
  searchData: {
    phone: '',
    loginName: '',
    name: ''
  },
  teamId: '',
  teamName: '',
  projectId: '',
  expandedKeys: [],
  expandedKeys1: [],
  autoExpandParent: true,
  autoExpandParent1: true,
  selectedKeys: [],
  suitableDataList: {
    dataSource: [],
    total: 0,
    stop:0,
    start:0
  },
  biz:{
    queryForm: {}
  },
  treeData: {},
  treeData1:{},
  loading: false,
  btnLoading: false,
  actionType: '',//edit编辑，detail详情，add新增
  detailData: {}, //详情数据
  // 表格数据
tableData: {
  dataSource: [],
  total: 0,
  stop:0,
  start:0
},
// 表格分页设置
pageConfig: {
  pageSize: Number.parseInt(config.smallPageSizeList[0]),
  pageNo: 1
},
pageConfig1: {
  pageSize: Number.parseInt(config.smallPageSizeList[0]),
  pageNo: 1
},
selectedRowKeys: [],
selectedRows: [],
teamModal:{
  visible: false
}
}

const tmpModule = {
  // namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态

          dispatch({type: 'queryAllPermission', payload: {}})
        } // end if
      }) // end listen
    },
  },
  
  effects: {
    //获取资源树
    * queryAllPermission ({payload}, {put, call, select}) {
      let {treeData,treeData1} = yield select(state => state[tmpModule.namespace])
      if(yield call(verifyCodeFun,{})){
        let {data, success} = yield call(queryAllPermission)
        if (data&&data !="") {
          let list = typeof(data) == 'string'?JSON.parse(data):data
          treeData = list
          treeData1 = list
            yield put({type: 'updateStore',payload: {treeData,treeData1}})
        }
      }
    },
    // 获取用户表格数据
    * getDetail ({payload}, {put, call, select}) {
      let {tableData,teamId} = yield select(state => state[tmpModule.namespace])
      tableData.dataSource = []
      let params = {
        id: payload.id?payload.id:teamId
      }
      let {data, success} = yield call(getDetail, params)
      if (data&&data !="") {
        let list = typeof(data.data) == 'string'?JSON.parse(data):data.data
        if(list.users){
          for(var item of list.users){
            item['teamName'] = list.teamName
            item['teamId'] = list.id
          }
        }
        tableData.dataSource = list.users
      }
      yield put({type: 'updateStore', payload: {...payload, tableData}})
    },
    // 获取弹窗表格数据
    * queryUserByOrg ({payload}, {put, call, select}) {
        let {suitableDataList,searchData,projectId} = yield select(state => state[tmpModule.namespace])
        suitableDataList.dataSource = []
        let params = {
          projectId: payload.id?payload.id:projectId,
          loginName: searchData.loginName,
          phone: searchData.phone,
          name: searchData.name
        }
        let {data, success} = yield call(queryUserByOrg, params)
        if (data&&data !="") {
          let list = typeof(data) == 'string'?JSON.parse(data):data
          suitableDataList.dataSource = list.userList
        }
        yield put({type: 'updateStore', payload: {...payload, suitableDataList}})
      },

     //删除
    * onDelete({payload}, {put, call, select}) {
      let params = {
        userId: payload.id,
        teamId: payload.teamId
      }
      let { success, msg, data } = yield call(onDelete, {...params})
      if(success){
        message.success('删除成功')
        yield put({type: 'getDetail', payload: {}})
      }
    },
    //删除团队
    * delTeam({payload}, {put, call, select}) {
      let {teamId,teamName} = yield select(state => state[tmpModule.namespace])
      let params = {
        id: teamId
      }
      let { success, msg, data } = yield call(delTeam, {...params})
      if(success){
        message.success('删除团队成功')
        teamName = ""
        yield put({type: 'queryAllPermission', payload: {}})
        yield put({type: 'getDetail', payload: {}})
      }
    },
    //编辑团队
    *submit({payload},{put,select,call}){
      let {teamId,teamName} = yield select(state => state[tmpModule.namespace])
      let params = {
        id: teamId,
        teamName:teamName
      }
      const { success, msg, data } = yield call(submit, {...params})

      if(success){
        message.success('编辑团队成功')
        yield put({type: 'queryAllPermission', payload: {}})
        yield put({type: 'getDetail', payload: {}})
      }
    },
    * addTeamUser({payload}, {put, call, select}) {
      let {selectedRows,teamId,teamModal,btnLoading} = yield select(state => state[tmpModule.namespace])
      yield put({type: 'updateStore', payload: {btnLoading: true}})
      let list = []
      for(var item of selectedRows){
        let obj={}
        obj['teamId'] = teamId
        obj['userId'] = item.id
        list.push(obj)
      }
      let params =  list
      let { success, msg, data } = yield call(addTeamUser, params)
      yield put({type: 'updateStore', payload: {btnLoading: false}})
      if(success){
        message.success('添加成功')
        teamModal.visible = !teamModal.visible

        yield put({type: 'getDetail', payload: {}})
      }
    },

    * selectedKeysChange ({payload}, {put, select, call}) {
      let {selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
      
      selectedRowKeys=payload.selectedRowKeys
      selectedRows=payload.selectedRows
      yield put({
        type: 'updateStore',
        payload: {
          selectedRowKeys,selectedRows
        }
      })
    },
  },
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
